package com.lance.answer.util;

import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import org.openqa.selenium.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * <p>识别验证码<p>
 *
 * @author : fengx
 * @since JDK8.0
 * create by fengx on 2021/1/21 14:45
 */
public class AnalysisIdentifyingCode {

    public static void takeScreenshot(WebDriver driver, String filePath) throws IOException {
        // 得到截图
        byte[] screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
        FileOutputStream fos = new FileOutputStream(filePath);
        fos.write(screenshot);
        fos.close();
    }

    //开始裁剪的位置和截图的宽和高
    public static BufferedImage createElementImage(WebDriver driver, String filePath, int x, int y, int width, int height)
            throws IOException {

        //BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(takeScreenshot(driver)));
        takeScreenshot(driver, filePath);
        //  System.exit(1);
        BufferedImage originalImage = ImageIO.read(new File(filePath));
        // 进行裁剪
        BufferedImage croppedImage = originalImage.getSubimage(x, y, width, height);
        return croppedImage;
    }

    public static String getVerificationCode(WebDriver driver, String path) {
        File imageFile = new File(path);
        try {
            imageFile.createNewFile();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        //    location = self.driver.find_element_by_xpath(
        //            '/html/body/div/div[2]/div[1]/div/form/div[4]/div[2]/img').location
        // //*[@id="app"]/div/div/div[2]/div/div[2]/div/p[2]/img
      //  WebElement element = driver.findElement(By.xpath("/html/body/div/div[2]/div[1]/div/form/div[4]/div[2]/img"));
        WebElement element = driver.findElement(By.xpath("//*[@id=\"app\"]/div/div/div[2]/div/div[2]/div/p[2]/img"));
        Dimension dimension = element.getSize();
        Point point = element.getLocation();
        try {
            //得到裁剪的图片
            BufferedImage image = createElementImage(driver, path, point.x, point.y,
                    dimension.width, dimension.height);
            //进行保存
            ImageIO.write(image, "png", imageFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 调用Tesseract
        ITesseract instance = new Tesseract();

        String result = null;
        try {
            File oldFile = new File(path);
            ImageUtil.cleanImage(oldFile,oldFile.getParent());
            result = instance.doOCR(new File(path));
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        //替换大小写及数字
        // result = result.replaceAll("[^a-z^A-Z^0-9]", "");
         result = result.replaceAll("[^a-z^A-Z^0-9]", "");
        return result;
    }






}
